package com.dxj.security.exception;
import com.dxj.response.R;
import com.dxj.sysEnum.SysHttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author dxj
 * @Description 自定义认证失败异常
 * @date 2024/7/28 20:03
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 设置响应内容类型为JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 设置HTTP状态码为401未授权
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 将Map转换为JSON字符串并写入响应
        try (PrintWriter out = response.getWriter()) {
            out.print(objectMapper.writeValueAsString(R.fail(SysHttpStatus.UNAUTHORIZED)));
        }
    }
}
